<?php

namespace app\admin\controller\paotui;

use app\admin\model\paotui\UserLevel;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户管理
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\paotui\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\paotui\Member;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->field("member.*,user_level.level_id,level.level_name")
                ->alias("member")
                ->join("paotui_user_level user_level","member.id=user_level.user_id","left")
                ->join("paotui_level level","level.id=user_level.level_id","left")
                ->where($where)

                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list->items() as &$v){
                //获取下单数量
                $postModel = new \app\admin\model\paotui\Post();
                $v['num'] = $postModel->where(['user_id'=>$v['id'],'status'=>['egt',2]])->count();
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function set_level($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $userLevelModel = new UserLevel();
                    if($userLevelInfo = $userLevelModel->where(['user_id'=>$row['id']])->find()){
                        $userLevelInfo->save(['level_id'=>$params['level_id']]);
                    }else{
                        $userLevelModel = new UserLevel();
                        $userLevelModel->save([
                            'user_id'=>$row['id'],
                            'level_id'=>$params['level_id']
                        ]);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        //获取会员等级
        $levelModel = new \app\admin\model\paotui\Level();
        $levelList = $levelModel->order("id asc")->select();
        $this->assign("levelList",$levelList);

        //获取当前会员等级
        $userLevelModel = new UserLevel();
        $userLevelInfo = $userLevelModel->where(['user_id'=>$row['id']])->find();
        $this->assign('user_level_id',empty($userLevelInfo['level_id'])?0:$userLevelInfo['level_id']);
        return $this->view->fetch();
    }


}
